// pages/user/user.js
const app = getApp();
const util = require('../../utils/util')
const { AuthLogout } = require('../../config/api')
const user = require('../../utils/user')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: {
      avatarUrl: 'https://img2.baidu.com/it/u=943569914,2714277101&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500',
      nickName: '点击登录',
    },
    hasLogin: false,
  },
  // 点击登录
  goLogin() {
    if (!app.globalData.hasLogin) {
      wx.navigateTo({
        url: '../login/login',
      })
    }
  },


  // 退出登录
  logout() {
    let that = this;
    wx.showModal({
      title: '退出登录',
      content: '确定退出登录当前帐号？',
      complete: (res) => {
        if (res.cancel) {
          return
        }

        if (res.confirm) {
          util.request(AuthLogout, {}, 'POST').then(res => {
            if (res.errno == 0) {
              app.globalData.hasLogin = false;
              wx.clearStorage()
              wx.reLaunch({
                url: './user',
              })
            }
          })
        }
      }
    })




  },
  onLoad(){
    let that = this;
    // 根据仓库中有无数据来 判断用户是否登录
    user.checkLogin().then(res=>{
      app.globalData.hasLogin=true;
      let userInfo = wx.getStorageSync('userInfo')
      that.setData({
        userInfo:userInfo,
        hasLogin:true
      });
    }).catch(()=>{
      app.globalData.hasLogin=false;
    })

    if (app.globalData.hasLogin) {
      this.setData({
        userInfo: wx.getStorageSync('userInfo'),
        hasLogin: true
      })
    }
  },
  onShow(options) {
    let that = this;
    // 根据仓库中有无数据来 判断用户是否登录
    user.checkLogin().then(res=>{
      app.globalData.hasLogin=true;
      let userInfo = wx.getStorageSync('userInfo')
      that.setData({
        userInfo:userInfo,
        hasLogin:true
      });
    }).catch(()=>{
      app.globalData.hasLogin=false;
    })

    if (app.globalData.hasLogin) {
      this.setData({
        userInfo: wx.getStorageSync('userInfo'),
        hasLogin: true
      })
    }
  },


})